// import { useCallback, useEffect } from 'react';
import BackPage from '@/components/BackPage';
import SaleBadge from '@/components/SaleBadge';
import SelectOne from '@/components/SelectOne';
import { allGoodsByCompany, removeGoods } from '@/services/commodity';
import { getQueryParams } from '@/utils/utils';
import { EllipsisOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Dropdown, Image, Menu, message, Space, Tag } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import ConfirmModal from './components/ConfirmModal';
import { optionEat, optionsUse } from './constants';
import styles from './index.less';

const OrderManage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const qs = getQueryParams();
  const [modalKey, setModalKey] = useState<string>('1');
  const [confirm, setConfirm] = useState<boolean>(false);

  const [list, setList] = useState<any[]>([]);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [goodsId, setGoodsId] = useState<string>('');
  const [imgsClick, setImgsClick] = useState<any[]>([]);
  // const [imgKey, setImgKey] = useState<number>(0);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      await allGoodsByCompany({ companyId: qs.id, pageSize: 4, pageIndex: currentPage }).then(
        (res) => {
          setTotal(res.total);
          setList(res.list);
          let arr: any[] = [];
          res.list.map((item: any) => {
            arr.push({ id: item.id, visible: false });
          });
          setImgsClick(arr);
        },
      );
    } catch (error) {
      console.log(error);
    }
  }, [currentPage, qs.id]);

  useEffect(() => {
    getList();
  }, [getList]);

  const actionFun = (record: any) => {
    setGoodsId(record.id);
  };

  const removedGoods = async () => {
    await removeGoods({ id: goodsId }).then(() => {
      setConfirm(false);
      getList();
      message.success('删除成功！');
    });
  };

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '商品编号',
      dataIndex: 'id',
      align: 'center',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '商品名称',
      align: 'center',
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: '商品图片',
      dataIndex: 'img',
      align: 'center',
      width: 200,
      render: (_, record) => {
        let current = JSON.stringify(record.img)
          .replace('[', '')
          .replace(']', '')
          .replace(/"/g, '')
          .replace(/\\/g, '')
          .split(',');

        return (
          <div className={styles.imgController} key={record.id}>
            {imgsClick.map((item, index: number) => {
              if (item.id === record.id) {
                return (
                  <div key={record.id}>
                    <Image
                      preview={{ visible: false }}
                      width={200}
                      src={`http://localhost:8090/dyh/upload_images/commodity/${current[0]}`}
                      onClick={() => {
                        let arr: any[] = imgsClick;
                        arr.splice(index, 1, { id: item.id, visible: true });
                        setImgsClick(JSON.parse(JSON.stringify(arr)));
                      }}
                      className={styles.goodsImgs}
                    />
                    <div style={{ display: 'none' }}>
                      <Image.PreviewGroup
                        preview={{
                          visible: item.visible,
                          onVisibleChange: (vis) => {
                            let arr: any[] = imgsClick;
                            arr.splice(index, 1, { id: item.id, visible: vis });
                            setImgsClick(JSON.parse(JSON.stringify(arr)));
                          },
                        }}
                      >
                        {current.map((items) => (
                          <Image
                            key={items}
                            src={`http://localhost:8090/dyh/upload_images/commodity/${items}`}
                          />
                        ))}
                      </Image.PreviewGroup>
                    </div>
                  </div>
                );
              } else {
                return;
              }
            })}
          </div>
        );
      },
    },
    {
      title: '单价',
      align: 'center',
      dataIndex: 'price',
    },
    {
      title: '库存',
      align: 'center',
      dataIndex: 'stock',
    },
    {
      title: '标签',
      align: 'center',
      width: 200,
      render: (_, record) => (
        <div className={styles.labels} key={record.id}>
          {record.type === '器械保健'
            ? optionsUse.map((items) => (
                <div key={items.value}>
                  {items.children.map((item) => (
                    <div key={item.value}>
                      {(item.value === record.typeUseOne || item.value === record.typeUseTwo) && (
                        <Tag color={items.color} key={item.value}>
                          {item.label}
                        </Tag>
                      )}
                    </div>
                  ))}
                </div>
              ))
            : optionEat.map((items) => (
                <div key={items.value}>
                  {items.children.map((item) => (
                    <div key={item.value}>
                      {(item.value === record.typeEatOne ||
                        item.value === record.typeEatTwo ||
                        item.value === record.typeEatThree) && (
                        <Tag color={items.color} key={item.value}>
                          {item.label}
                        </Tag>
                      )}
                    </div>
                  ))}
                </div>
              ))}
        </div>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <div key={record.id}>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item
                  className={styles.poster}
                  onClick={() => {
                    if (record.ispush === '0') {
                      setModalKey('1');
                      setConfirm(true);
                    } else {
                      message.error(
                        `该商品正在${
                          record.ispush === '1' ? '轮播图' : '首页商品'
                        }投放中，无法继续投放`,
                      );
                    }
                  }}
                >
                  广告投放
                </Menu.Item>
                <Menu.Item
                  className={styles.delete}
                  onClick={() => {
                    setModalKey('2');
                    setConfirm(true);
                  }}
                >
                  删除
                </Menu.Item>
              </Menu>
            }
            overlayClassName={styles.dropDownStyle}
            trigger={['click']}
            onVisibleChange={() => actionFun(record)}
          >
            <Space>
              <EllipsisOutlined style={{ fontSize: 26, color: '#999', cursor: 'pointer' }} />
            </Space>
          </Dropdown>
        </div>,
      ],
    },
  ];

  return (
    <BackPage thisRoute={'/goodsmanage'} lastRoute={'商品管理'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'商品编号'}
          fromWhere={'goods'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          bordered
          dataSource={selectList.length !== 0 ? selectList : list}
          actionRef={actionRef}
          cardBordered={false}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 4, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        {confirm && (
          <ConfirmModal
            goodsId={goodsId}
            ifDelete={modalKey}
            getList={getList}
            handleCancel={function (): void {
              setConfirm(false);
            }}
            handleSeal={() => {
              modalKey === '2' ? removedGoods() : '';
            }}
          />
        )}
        <SaleBadge />
      </div>
    </BackPage>
  );
};
export default OrderManage;
